import { createChatListApi} from '@/api/chatlist'
import { getChatMessageListApi } from '@/api/chatmessage'
import type { ChatMessage } from '@/types/chatmessage'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useUserStore } from './user'
import { useProductDetailStore } from './productDetail'
import { useWebSocket } from '@/utils/websocket'
import type { ChatListType } from '@/types/chatlist'
import { useChatListStore } from './chatList'
import { formatISO8601 } from '@/utils/formatDate'
export const useChatMessageStore = defineStore('chatMessage', () => {
  const { send, disconnect, connect } = useWebSocket()

  // 存储当前聊天列表,聊天列表只会由买家创建，卖家不会创建聊天列表
  const chatList = ref<ChatListType>({
    id: '',
    productId: '',
    productImage: '',
    fromUserId: '',
    fromUserNick: '',
    fromUserAvatar: '',
    toUserId: '',
    toUserNick: '',
    toUserAvatar: '',
    chatMessage: {
      chatListId: '',
      fromUserId: '',
      toUserId: '',
      fromUserNick: '',
      toUserNick: '',
      fromUserAvatar: '',
      toUserAvatar: '',
      content: '',
      sendTime: '',

    },
    noReadCount: 0,
  })
  // 存储聊天消息
  const messages = ref<ChatMessage[]>([])
  // 存储文字消息
  const content = ref<string>('')
  // 存储单条消息
  const message = ref<ChatMessage>({
    chatListId: '',
    fromUserId: '',
    toUserId: '',
    fromUserNick: '',
    toUserNick: '',
    fromUserAvatar: '',
    toUserAvatar: '',
    content: '',
    sendTime: '',
  })
  // 标记聊天窗口打开的聊天列表id
  const isChatMessageOpened = ref<string>('')

  // 根据productId,fromUserId, toUserId来从后端获取对应的聊天记录方法
  const getChatDetail = async (productId: string, toUserId: string) => {
    // 重置数据
    chatList.value = {
      id: '',
      productId: '',
      productImage: '',
      fromUserId: '',
      fromUserNick: '',
      fromUserAvatar: '',
      toUserId: '',
      toUserNick: '',
      toUserAvatar: '',
      chatMessage: {
        chatListId: '',
        fromUserId: '',
        toUserId: '',
        fromUserNick: '',
        toUserNick: '',
        fromUserAvatar: '',
        toUserAvatar: '',
        content: '',
        sendTime: '',
      },
      noReadCount: 0,
    }
    messages.value = []
    message.value = {
      chatListId: '',
      fromUserId: '',
      toUserId: '',
      fromUserNick: '',
      toUserNick: '',
      fromUserAvatar: '',
      toUserAvatar: '',
      content: '',
      sendTime: '',
    }
    try {
      // 在useChatListStore中的chatList中查找是否有与之对应的聊天列表
      useChatListStore().chatList.forEach(item => {
        if (
          item.productId === productId &&
          (item.toUserId === useUserStore().user.id ||
            item.fromUserId === useUserStore().user.id) &&
          (item.toUserId === toUserId || item.fromUserId === toUserId)
        ) {
          chatList.value = item
          console.log('找到与之对应的聊天列表')
        }
      })
      // 如果有与之对应的聊天列表，就去获取该聊天列表的聊天记录
      if (chatList.value.id !== '') {
        // 如果有与之对应的聊天列表，就去获取该聊天列表的聊天记录
        const response = await getChatMessageListApi(chatList.value.id)
        if (response.code === 0) {
          messages.value = response.data
        } else {
          console.error('获取聊天记录失败', response.msg)
          ElMessage.error('获取聊天记录失败')
        }
      } else {
        console.log('没有找到与之对应的聊天列表')
      }
    } catch (error) {
      console.error('获取聊天记录失败', error)
      ElMessage.error('获取聊天记录失败')
    }
  }

  // 发送消息
  const sendMessage = async () => {
    // 判断是否有聊天列表
    if (chatList.value.id !== '') {
      // 存在旧的聊天列表，发送消息
      // 要判断该聊天列表关联的商品是自己的还是对方的
      if (useProductDetailStore().productDetail.userId === useUserStore().user.id) {
        // 如果是自己的商品，自己是卖家，toUserId就是买家的id
        message.value = {
          chatListId: chatList.value.id,
          // 此处要发送给对方的id，也就是买家ID
          fromUserId: chatList.value.toUserId,
          toUserId: chatList.value.fromUserId,
          fromUserNick: chatList.value.toUserNick,
          toUserNick: chatList.value.fromUserNick,
          fromUserAvatar: chatList.value.toUserAvatar,
          toUserAvatar: chatList.value.fromUserAvatar,
          content: content.value,
          // 当前时间
          sendTime: formatISO8601(new Date()),
        }
      } else {
        // 如果不是自己的商品，自己是买家，toUserId就是卖家的id
        message.value = {
          chatListId: chatList.value.id,
          fromUserId: chatList.value.fromUserId,
          // 此处要发送给对方的id，也就是卖家ID
          toUserId: chatList.value.toUserId,
          fromUserNick: chatList.value.fromUserNick,
          toUserNick: chatList.value.toUserNick,
          fromUserAvatar: chatList.value.fromUserAvatar,
          toUserAvatar: chatList.value.toUserAvatar,
          content: content.value,
          // 当前时间
          sendTime: formatISO8601(new Date()),
        }
      }
      // 找到对应的聊天列表，将消息添加到聊天记录中
      useChatListStore().chatList.find(item => item.id === chatList.value.id)!.chatMessage =
        message.value
      useChatMessageStore().messages.push(message.value)
      send(message.value)
      // 清空输入框
      content.value = ''
    } else {
      // 只有买家才会，创建新的聊天列表,返回值应该是chatlist
      try {
        // 创建新的聊天列表
        const res = await createChatListApi(
          useProductDetailStore().productDetail.userId,
          useProductDetailStore().productDetail.id,
        )
        if (res.code === 0) {
          // 将新的聊天列表添加到聊天列表中
          useChatListStore().chatList.push(res.data)
          // 将新的聊天列表赋值给当前聊天的chatList
          chatList.value = res.data
          message.value = {
            chatListId: chatList.value.id,
            fromUserId: chatList.value.fromUserId,
            toUserId: chatList.value.toUserId,
            fromUserNick: chatList.value.fromUserNick,
            toUserNick: chatList.value.toUserNick,
            fromUserAvatar: chatList.value.fromUserAvatar,
            toUserAvatar: chatList.value.toUserAvatar,
            content: content.value,
            // 当前时间
            sendTime: formatISO8601(new Date()),
          }
          // 找到对应的聊天列表，将消息添加到聊天记录中
          useChatListStore().chatList.find(item => item.id === chatList.value.id)!.chatMessage =
            message.value
          useChatMessageStore().messages.push(message.value)
          send(message.value)
          // 清空输入框
          content.value = ''
        } else {
          console.log('创建聊天列表失败', res.msg)
        }
      } catch (error) {
        console.error('创建聊天列表失败', error)
      }
    }
  }

  // 关闭聊天连接
  const closeChat = () => {
    // 关闭聊天连接
    disconnect()
  }
  // 建立聊天连接
  const openChat = (userId: string) => {
    connect(userId)
  }
  
  return {
    getChatDetail,
    sendMessage,
    closeChat,
    openChat,
    message,
    messages,
    content,
    chatList,
    isChatMessageOpened,
  }
})
